<template>
  <div class="app-container">
    <y-table ref="gridRef" v-bind="listOptions" @toolbar-button-click="toolbarButtonClickEvent">
      <template #editcolumn="{ row, column }">
        <div v-if="!editColumnFlag">
          <el-select v-if="column.field === 'isTeaching'" size="mini" style="width: 80px" v-model="row[column.field]"
            @change="updateById(row, column)">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <el-input v-else size="mini" v-model="row[column.field]" @change="updateById(row, column)"></el-input>
        </div>
        <div v-else>
          {{ column.field === 'isTeaching' ? row[column.field] === 1 ? '是' : '否' : row[column.field] }}
        </div>
      </template>
    </y-table>
    <y-form-dialog :title="formOptions.title" ref="dialogFormRef" :form-options="formOptions"
      @confirm="confirmForm"></y-form-dialog>
    <y-form-dialog :title="formOptions.title" ref="dialogInfoRef" :form-options="detailFormConfig"
      @confirm="_ => { }"></y-form-dialog>
  </div>
</template>

<script>

import { getCollegeList, updateCollegeField, bathDeleteCollege, addCollege } from '@/api/base/college' // 接口

import listMixin from '@/mixins/listMixin'

export default {
  mixins: [listMixin],
  data() {
    return {
      //编辑模式开关
      editColumnFlag: true,
      //是否教学单位
      options: [
        { value: 1, label: '是' },
        { value: 0, label: '否' }
      ],
      // 表格配置
      listOptions: {
        // 导出
        exportConfig: { fileName: '学院信息导出', moudle: 'XYXXDC' },
        // 导入
        importConfig: { fileName: '学院信息导入', module: 'XYXXDR' },
        // 默认查询数据
        defaultQueryData: {
          // form
          form: {},
          // 分页
          page: {
            pageSize: 50
          },
          // 其他查询参数
          params: {}
        },
        // 获取数据方法
        dataMethod: getCollegeList,
        // 表单配置
        formOptions: {
          items: [
            {
              field: 'collegeCode', title: '院所名称',
              itemRender: {
                name: 'ZSelect',
                props: {
                  dictCode: 'college_list_easy'
                }
              }
            },
            {
              field: 'keywords', title: '负责人|秘书姓名',
              itemRender: {
                name: 'VxeInput'
              }
            }
          ]
        },
        // 表格配置
        tableOptions: {
          rowConfig: {
            keyField: 'tid'
          },
          toolbarConfig: {
            // 按钮组
            buttons: [
              { name: '新增', code: 'add', status: 'primary', icon: 'vxe-icon-add' },
              { name: '开启编辑模式', code: 'openEdit', status: 'primary', icon: 'vxe-icon-add' },
              { name: '关闭编辑模式', code: 'closeEdit', status: 'primary', icon: 'vxe-icon-add' },
              { name: '批量删除', code: 'batchDelete', status: 'danger', icon: 'vxe-icon-delete' }
            ],
            // 工具栏
            tools: [
              // { type: 'button', code: 'DivCode', icon: 'vxe-icon-edit', circle: true },
            ]
          },
          // 表格列
          columns: [
            { type: 'checkbox', width: 60 },
            { type: 'seq', width: 60 },
            { field: 'collegeCode', width: 80, title: '院所代码' },
            { field: 'collegeName', minWidth: 120, title: '院所名称', slots: { default: 'editcolumn' } },
            { field: 'collegeNameEn', minWidth: 150, title: '院所英文名称', visible: false },
            { field: 'collegeAbbrev', width: 100, title: '院所简称', slots: { default: 'editcolumn' } },
            { field: 'collegeCodeInc', minWidth: 150, title: '数据中心单位编码', visible: false },
            { field: 'managerName', width: 100, title: '教学负责人', slots: { default: 'editcolumn' } },
            { field: 'managerOffice', minWidth: 150, title: '教学负责人办公地点', visible: false },
            { field: 'managerContact', minWidth: 120, title: '教学负责人联系电话', slots: { default: 'editcolumn' }, visible: false },
            { field: 'managerEmail', minWidth: 150, title: '教学负责人电子邮箱', visible: false },
            { field: 'staffName', minWidth: 150, title: '教学秘书', slots: { default: 'editcolumn' } },
            { field: 'staffOffice', minWidth: 150, title: '教学秘书办公地点', visible: false },
            { field: 'staffContact', minWidth: 120, title: '教学秘书联系电话', slots: { default: 'editcolumn' }, visible: false },
            { field: 'staffEmail', minWidth: 150, title: '教学秘书电子邮箱', visible: false },
            { field: 'collegeUrl', minWidth: 150, title: '院所网址', slots: { default: 'editcolumn' } },
            { field: 'isTeaching', width: 100, title: '教学单位', slots: { default: 'editcolumn' } },
            { field: 'orderNum', width: 100, title: '排序号', slots: { default: 'editcolumn' } },
            { field: 'collegeMemo', minWidth: 100, title: '备注', visible: false },
            {
              title: '操作',
              width: 130,
              cellRender: {
                name: 'buttons',
                options: [
                  { content: '修改', name: 'edit' },
                  {
                    content: '更多', dropdowns: [
                      { content: '详情', name: 'info' },
                      { content: '删除', name: 'delete' }
                    ]
                  }
                ],
                events: {
                  click: ({ name, row }) => {
                    switch (name) {
                      case 'edit':
                        this.openFormDialog({ row, refName: 'dialogFormRef' })
                        break
                      case 'delete':
                        this.deleteRow({ row, deleteMethod: (row) => this.bathDeleteCollege(row.tid) })
                        break
                      case 'info':
                        this.openFormDialog({ row, refName: 'dialogInfoRef' })
                        break
                      default:
                        break
                    }
                  }
                }
              }
            }
          ]
        }
      },
      formOptions: {
        title: '学院信息',
        titleWidth: 140,
        items: [
          {
            required: true, field: 'collegeCode', title: '院所代码', itemRender: {
              name: 'VxeInput',
            }
          },
          {
            required: true, field: 'collegeName', title: '院所名称', itemRender: {
              name: 'VxeInput',
            }
          },
          {
            required: true, field: "collegeAbbrev", title: "院所简称", itemRender: {
              name: 'VxeInput'
            }
          },
          {
            required: true, field: 'isTeaching', title: '是否教学单位', dictCode: 'sf',
            itemRender: {
              name: 'ElSelect',
              options: [
                { label: '是', value: 1 },
                { label: '否', value: 0 }
              ],
            }
          },
          {
            required: true, field: 'orderNum', title: '排序号', itemRender: {
              name: 'VxeInput',
              props: { type: 'number' }
            }
          },
          {
            field: "collegeCodeInc", title: "数据中心单位编码", itemRender: {
              name: 'VxeInput'
            }
          },
          {
            field: "collegeUrl", title: "院所网址", itemRender: {
              name: 'VxeInput'
            }
          },
          {
            field: "managerName", title: "教学负责人", itemRender: {
              name: "VxeInput"
            }
          },
          {
            field: "managerOffice", title: "教学负责人办公地点", itemRender: {
              name: "VxeInput"
            }
          },
          {
            field: "managerContact", title: "教学负责人联系电话", itemRender: {
              name: "VxeInput"
            }
          },
          {
            field: "managerEmail", title: "教学负责人电子邮箱", itemRender: {
              name: 'VxeInput'
            },
            rules: [{
              pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
              message: '请输入正确的邮箱格式'
            }]
          },
          {
            field: "staffName", title: "教学秘书", itemRender: {
              name: "VxeInput"
            }
          },
          {
            field: "staffOffice", title: "教学秘书办公地点", itemRender: {
              name: "VxeInput"
            }
          },
          {
            field: "staffContact", title: "教学秘书联系电话", itemRender: {
              name: "VxeInput"
            }
          },
          {
            field: "staffEmail", title: "教学秘书电子邮箱", itemRender: {
              name: 'VxeInput'
            },
            rules: [{
              pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
              message: '请输入正确的邮箱格式'
            }]
          },
          {
            field: 'collegeMemo', title: '备注', itemRender: {
              name: 'VxeTextarea',
            },
            rules: [{
              max: 2000,
              message: '请限制在2000字内'
            }]
          },
        ]
      },
    }
  },
  computed: {
    detailFormConfig() {
      return {
        ...this.formOptions,
        border: true,
        items: this.formOptions.items.filter(d => d.field).map(({ field, title }) => {
          return { field, title }
        })
      }
    }
  },
  /**
   * 组件挂载时异步执行的方法
   */
  async mounted() {
    // 动态设置查询参数
    // 此处的目的是根据某些条件或逻辑动态地设置组件的查询参数，以便在加载数据前做好准备
    await this.setFormQuery()

    // 加载数据
    // 通过refs引用调用loadData方法来加载数据
    this.$refs.gridRef.loadData()
  },
  methods: {
    /**
     * 工具栏按钮点击事件处理函数
     * @param {Object} event - 事件对象，包含按钮代码
     * 该函数根据点击的工具栏按钮代码，执行不同的操作
     */
    toolbarButtonClickEvent({ code }) {
      switch (code) {
        case 'openEdit':
          // 打开编辑模式
          this.editColumnFlag = false
          break
        case 'closeEdit':
          // 关闭编辑模式
          this.editColumnFlag = true
          break
        case 'add':
          // 执行添加操作，打开表单对话框
          this.openFormDialog({ row: null, refName: 'dialogFormRef' })
          break
        case 'batchDelete':
          // 批量删除
          let checkboxRecords = this.getCheckboxRow()
          if (checkboxRecords.length === 0) {
            this.$message.warning('请先选择要删除的记录')
            return
          }
          this.$confirm('确认删除选中的记录吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.deleteById(checkboxRecords)
          })
          break
        default:
          break
      }
    },
    //提交表单
    async confirmForm(form) {
      return new Promise((resolve, reject) => {
        this.saveOrUpdate(form).then(res => {
          if (res.status) {
            this.$message.success(res.message)
            this.$refs.gridRef.loadData()
            resolve(true)
          }
        })
      })
    },
    // 保存或修改
    saveOrUpdate(form) {
      if (form.tid) {
        return updateCollegeField(form)
      } else {
        return addCollege(form)
      }
    },
    // 修改
    updateById(row) {
      updateCollegeField(row).then(res => {
        if (res.status) {
          this.$message.success(res.message)
          this.$refs.gridRef.loadData()
        }
      })
    },
    // 删除
    deleteById(row) {
      bathDeleteCollege(row.tid || row.map(item => item.tid).join(',')).then(res => {
        if (res.status) {
          this.$message.success(res.message)
          this.$refs.gridRef.loadData()
        }
      })
    },
    async setFormQuery() {
      // this.listOptions.defaultQueryData.form.pageSize = 50
      // this.listOptions.defaultQueryData.form.pageNum = 1
    },
    getRadioRow() {
      return this.$refs.gridRef.$refs.gridRef.getRadioRecord()
    },
    getCheckboxRow() {
      return this.$refs.gridRef.$refs.gridRef.getCheckboxRecords()
    }
  }
}
</script>

<style lang="scss" scoped></style>
